package com.soboot.auth.service;

import cn.hutool.core.util.StrUtil;
import com.soboot.base.model.BaseUser;
import com.soboot.response.Result;
import com.soboot.system.feign.UserInfoFeignClient;
import com.soboot.system.vo.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * @Author:
 * @createTime: 2022年09月20日 16:08:09
 * @version:
 * @Description: 验证入口
 * @Copyright:
 */
@Service
public class BaseUserDetailService implements UserDetailsService {

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Result<UserInfoVO> result = userInfoFeignClient.loginByUsername(username);
        UserInfoVO userInfoVO = result.getData();
        if(null == userInfoVO){
            throw new UsernameNotFoundException(StrUtil.format("{}用户不存在", username));
        }

        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(userInfoVO.getPermissions().toArray(new String[0]));

        BaseUser baseuser = new BaseUser(userInfoVO.getId(),userInfoVO.getNickName(),userInfoVO.getUserName(),
                userInfoVO.getPassword(),true,true,true,true
        ,authorities);

        return baseuser;
    }
}
